#include <unistd.h>
#include <fcntl.h>

int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len) {
    struct flock fl;

    fl.l_type = type;
    fl.l_start = offset;
    fl.l_whence = whence;
    fl.l_len = len;

    return fcntl(fd, cmd, &fl);
}

pid_t lock_test(int fd, int type, off_t offset, int whence, off_t len) {
    struct flock fl;

    fl.l_type = type;
    fl.l_start = offset;
    fl.l_whence = whence;
    fl.l_len = len;

    if (fcntl(fd, F_GETLK, &fl) < 0)
        return -1;

    if (fl.l_type == F_UNLCK)
        return 0;

    return fl.l_pid;
}
